﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using Microsoft.WindowsCE.Forms;
namespace TTBox
{
    public enum PanelType { Main, Msg, SysConfig, DispatchAsk, SReport, Input, Login };
    public partial class Form_Main : Form
    {

        bool m_bRunCmd = false;
        Queue m_qRecvCmd = new Queue();

        LoginPanel m_lp;
        MainScreenPanel m_msp;
        MsgPanel m_msgp;
        BoxStatus m_bs;
        SysConfigPanel m_scp;
        SendAndWaitPanel m_sawp;
        DispatchAskPanel m_dap;
        DispatchConfirmPanel m_dcp;
        NaviPanel m_nvp;
        InputPanel m_ip;
        bool m_bSetTime = false;
        SReportPanel m_srp;
        static public Form_Main Main = null;

        public bool m_bLogined = false;
        public string m_strIMEI = "000000000000000";

        public string StartLoc = "";

        //MsgWindow m_msgWin;

        DateTime m_dtSOSDisable = System.DateTime.Now;

        public bool IsSendAndWait { get { return m_sawp.Visible; } }

        public bool IsNeedSetTopMost = false;

        public void SetTopMost(bool arg_b)
        {
            this.TopMost = arg_b;
        }

        

        public Form_Main()
        {



            InitializeComponent();
            StartLoc = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName) + "\\";




            m_qRecvCmd = new Queue();
            m_bRunCmd = false;
            Main = this;

            DeviceManager.setBackLightTimeOut(StoreData.getInstance().BackLightSecs);
            DeviceManager.setVolume(StoreData.getInstance().SoundVol);
            DeviceManager.setBackLightValue(StoreData.getInstance().BackLightLevel);


            this.WindowState = FormWindowState.Maximized;
           // CmdTalker.getInstance().initial();
            m_bs = new BoxStatus(); 
            this.Controls.Add(m_bs);
            m_lp = new LoginPanel();
            this.Controls.Add(m_lp);
            m_msp =new MainScreenPanel();
            this.Controls.Add(m_msp);
            m_msgp = new MsgPanel();
            this.Controls.Add(m_msgp);
            //this.Controls.Add(m_st);
            m_sawp = new SendAndWaitPanel();
            this.Controls.Add(m_sawp);
            m_srp = new SReportPanel();
            this.Controls.Add(m_srp);
            m_scp = new SysConfigPanel();
            m_scp.Visible = true;
            m_scp.BringToFront();
            m_scp.Visible = false;
            this.Controls.Add(m_scp);

            m_nvp = new NaviPanel();
            this.Controls.Add(m_nvp);

            this.Controls.Add(m_ip);
            m_dap = new DispatchAskPanel();
            this.Controls.Add(m_dap);
            m_dcp = new DispatchConfirmPanel();
            this.Controls.Add(m_dcp);

            m_ip = new InputPanel();
            this.Controls.Add(m_ip);

            m_bs.Left = (this.Width - m_bs.Width);
            m_bs.BringToFront();
            m_bs.Visible = true;

            CmdTalker.getInstance().initial();
            //CmdTalker.getInstance().SendCMD("AT$MSGQCL");

            ChangeToLogin();

            ChangeUIFace(Color.White, Color.Black);

            //this.m_bs.BringToFront();
            //this.m_bs.Left = this.Width - this.m_bs.Width;
            //m_st.BringToFront();
            //m_lp.BringToFront();


            
            this.timer_Checker.Enabled = true;
            this.resetBackLightTimeout();

            //m_msgWin = new MsgWindow();
            
        }

        public void ChangeUIFace(Color arg_cFore, Color arg_cBack)
        {

            foreach (Control c in this.Controls)
            {
                if (c is UserControl)
                    UIUtility.ChangeFace(c, arg_cFore, arg_cBack);
            }
        }
        public void DisableUIButton()
        {
            foreach (Control c in this.Controls)
            {
                if (c is UserControl)
                    UIUtility.ButtonControl(c, false);
            }
        }
        public void EnableUIButton()
        {
            foreach (Control c in this.Controls)
            {
                if (c is UserControl)
                    UIUtility.ButtonControl(c, true);
            }
        }

        public void SendTTS(string arg_strTTS)
        {
            this.m_nvp.SendTTS(arg_strTTS);
        }
        public void MoveToMarkView(string arg_strLon, string arg_strLat)
        {
            this.m_nvp.MoveToMarkView(arg_strLon, arg_strLat);
        }


        public void SetMyPOI(string arg_strName, string arg_strLon, string arg_strLat)
        {
            this.m_nvp.SetPOI(arg_strName, arg_strLon, arg_strLat);
        }

        public MainScreenPanel Screen_MainScreen { get { return this.m_msp; } }
        public DispatchAskPanel Screen_AskScreen { get { return this.m_dap; } }
        public DispatchConfirmPanel Screen_ConfirmScreen { get { return this.m_dcp; } }

        public void ShowWaitingPanel()
        {
            DisableUIButton();
            m_sawp.Width = this.Width - 40;
            m_sawp.Left = (this.Width - m_sawp.Width) / 2;
            m_sawp.Top = (this.Height - m_sawp.Height) / 2;
            m_sawp.Visible = true;
            m_sawp.BringToFront();
            this.Refresh();
        }

        public void HideWaitingPanel()
        {
            m_sawp.Visible = false;
            m_sawp.SendToBack();
            this.Refresh();
            EnableUIButton();
        }


        public string getCurrStatusChar()
        {
            return this.m_msp.CurrStatus;
        }

        public string getJobID()
        {
            return this.m_msp.CurrRunOrderID;
        }

        public void SetCurrStatus(TaxiStatus arg_ts)
        {
            
            this.m_msp.setStatus(arg_ts);
            
        }


        //TODO: 091230
        public void CheckNaviStatus()
        {
            if (m_nvp.CheckIsNeedShow())
            {
                ChangeToNavi();
            }
        }

        public void ChangeToDispatchAsk(string arg_strCMD)
        {
            //TODO:如果是在導般模式, 要先切回去
            m_nvp.HideNavi();


            HideAllPanel();
            m_dap.initial(arg_strCMD);
            m_dap.Visible = true;
            m_dap.BringToFront();

        }

        public void ChangeToDispatchConfirm(string arg_strCMD)
        {
            //TODO:如果是在導般模式, 要先切回去
            m_nvp.HideNavi();


            HideAllPanel();
            m_dcp.initial(arg_strCMD, DispatchConfirmPanel.ConfirmPanelType.DispatchConfirm, -1);
            m_dcp.Visible = true;
            m_dcp.BringToFront();

        }

        public void ChangeToBillInputPanel(string arg_strOrderID)
        {
            HideAllPanel();
            m_ip.initial(0, arg_strOrderID);
            m_ip.Visible = true;
            m_ip.BringToFront();

        }


        public void SetDestByLonLat(string arg_strLon, string arg_strLat)
        {
            m_nvp.SetDestByLonLat(arg_strLon, arg_strLat);
        }

        public void ChangeToMessageRecv(string arg_strCMD)
        {
            //TODO:如果是在導般模式, 要先切回去
            m_nvp.HideNavi();


            HideAllPanel();
            m_dcp.initial(arg_strCMD, DispatchConfirmPanel.ConfirmPanelType.MessageRecv, -1);
            m_dcp.Visible = true;
            m_dcp.BringToFront();

        }

        public void ChangeToNavi()
        {
            if (StoreData.getInstance().IsPAPAGO)
            {
                m_nvp.ShowNavi();
            }
            else
            {
                HideAllPanel();
                m_nvp.Visible = true;
                m_nvp.BringToFront();
                this.Refresh();
                m_nvp.ShowNavi();
            }
        }
        public void ChangeToJobRead(string arg_strCMD, int arg_nIndex)
        {
            m_dcp.initial(arg_strCMD, DispatchConfirmPanel.ConfirmPanelType.JobRead, arg_nIndex);
            m_dcp.Visible = true;
            m_dcp.BringToFront();
        }
        public void ChangeToMessageRead(string arg_strCMD, int arg_nIndex)
        {
            m_dcp.initial(arg_strCMD, DispatchConfirmPanel.ConfirmPanelType.MessageRead, arg_nIndex);
            m_dcp.Visible = true;
            m_dcp.BringToFront();
        }
        public void ChangeToReserveJobMessageRead(string arg_strCMD)
        {
            m_dcp.initial(arg_strCMD, DispatchConfirmPanel.ConfirmPanelType.ReserveJobRead, -1);
            m_dcp.Visible = true;
            m_dcp.BringToFront();
        }

        private void HideAllPanel()
        {
            foreach (Control c in this.Controls)
            {
                if (c is UserControl)
                {
                    c.Visible = false;
                }
            }
        }


        public void ChangeToMainScreen()
        {
            HideAllPanel();
            m_msp.Visible = true;
            m_msp.BringToFront();
            m_bs.Left = (this.Width - m_bs.Width);
            m_bs.BringToFront();
            m_bs.Visible = true;
            Screen_MainScreen.checkReserveJobButton();
            Screen_MainScreen.disableButtonOneSec();

            //TODO: 091230 訊息完, 先暫不切回來, 不然會很卡..
            //CheckNaviStatus();
        }

        public void ChangeToLogin()
        {
            HideAllPanel();
            m_lp.Visible = true;
            m_lp.BringToFront();
            m_lp.initial();
            m_bs.Left = (this.Width - m_bs.Width);
            m_bs.BringToFront();
            m_bs.Visible = true;

            m_bs.Left = (this.Width - m_bs.Width);
            m_bs.BringToFront();
            m_bs.Visible = true;

        }

        public void ChangeToMsg()
        {
            HideAllPanel();
            m_msgp.Visible = true;
            m_msgp.initial(MsgPanel.MsgType.Msg);
            m_msgp.BringToFront();
        }


        public void ChangeToDispatchMsg()
        {
            HideAllPanel();
            m_msgp.Visible = true;
            m_msgp.initial(MsgPanel.MsgType.Dispatch);
            m_msgp.BringToFront();
        }

        public void ChangeToReserveJobMsg()
        {
            HideAllPanel();
            m_msgp.Visible = true;
            m_msgp.initial(MsgPanel.MsgType.ReserveJob);
            m_msgp.BringToFront();
        }


        public void ChangeToSReport()
        {
            HideAllPanel();
            m_srp.initial();
            m_srp.Visible = true;
            m_srp.BringToFront();
            m_bs.Visible = false;
        }

        public void ChangeToSysConfig()
        {
            HideAllPanel();
            m_scp.Visible = true;
            m_scp.initial();
            m_scp.BringToFront();
            m_bs.Visible = false;
        }

        public void ChangeToInputPanel()
        {
            HideAllPanel();
            m_ip.Visible = true;
            m_ip.BringToFront();
        }

        public void setBoxStatus(BoxStatusItem arg_bsi, bool arg_bShow)
        {
            switch (arg_bsi)
            {
                case BoxStatusItem.GPRS:
                    m_bs.setGPRSStatus(arg_bShow);
                    break;
                case BoxStatusItem.GPS:
                    m_bs.setGPSStatus(arg_bShow);
                    break;
                case BoxStatusItem.ACC:
                    m_bs.setACCStatus(arg_bShow);
                    break;
                case BoxStatusItem.Server:
                    m_bs.setServerStatus(arg_bShow);
                    break;
                case BoxStatusItem.Box:
                    m_bs.setBoxConn(arg_bShow);
                    break;
            }
        }

        public bool getBoxStatus(BoxStatusItem arg_bsi)
        {
            switch (arg_bsi)
            {
                case BoxStatusItem.GPRS:
                    return m_bs.GPRSStatus;
                case BoxStatusItem.GPS:
                    return m_bs.GPSStatus;
                case BoxStatusItem.ACC:
                    return m_bs.ACCStatus;
                case BoxStatusItem.Server:
                    return m_bs.ServerStatus;
            }
            return false;
        }

        public void addCmdToQueue(string arg_strCmd)
        {

            lock (m_qRecvCmd)
            {
                m_qRecvCmd.Enqueue(arg_strCmd);
            }

        }

        DateTime dtCheckBox = System.DateTime.Now;
        DateTime dtCheckBoxAcc = System.DateTime.Now;
        DateTime dtLastServerCheck = System.DateTime.Now;

        string strLastInputStatus = "22222222";
        public void updateLastServerCheck()
        {
            dtLastServerCheck = System.DateTime.Now.Add(new TimeSpan(0, 15, 0));
        }
        int nCMDIndex = 0;

        DateTime dtLastSetSystemDT = System.DateTime.Now;
        

        DateTime dtBackLightTimeout = System.DateTime.Now.AddSeconds(DeviceManager.readBackLightTimeOut());

        public void resetBackLightTimeout()
        {
            dtBackLightTimeout = System.DateTime.Now.AddSeconds(DeviceManager.readBackLightTimeOut());
            DeviceManager.setBackLightOn();
        }

        bool m_bIsTimer = false;
        int m_nTimerExitCount = 0;
       // DateTime m_dtCheckOnTop = System.DateTime.Now.AddSeconds(3);
        private void timer_Checker_Tick(object sender, EventArgs e)
        {
            try
            {
                if (m_bIsTimer && m_nTimerExitCount < 30)
                {
                    m_nTimerExitCount += 1;
                    return;
                }

                m_bIsTimer = true;
                m_nTimerExitCount = 0;
                if (IsNeedSetTopMost)
                {
                    SetTopMost(true);
                    IsNeedSetTopMost = false;
                    m_msp.dtReNavi = System.DateTime.Now.AddHours(1000);
                }

                /*
                if (m_dtCheckOnTop < System.DateTime.Now)
                {
                    m_dtCheckOnTop = System.DateTime.Now.AddSeconds(3);
                    this.SetTopMost(true);
                    this.BringToFront();
                    this.Refresh();
                    m_msp.SetNaviWindow();
                }*/

                this.button_Close.BringToFront();
                this.button_Initial.BringToFront();
                this.button_Log.BringToFront();

                CmdTalker.getInstance().doGPRSCheck();
                CmdTalker.getInstance().doGPSCheck();

                if (this.dtBackLightTimeout < System.DateTime.Now)
                {
                    if (this.TopMost)
                    {
                        DeviceManager.setBackLightOff();
                    }
                    dtBackLightTimeout = System.DateTime.Now.AddSeconds(DeviceManager.readBackLightTimeOut());
                }


                //check cmd
                //if (m_bRunCmd)
                {
                    lock (m_qRecvCmd)
                    {
                        if (m_qRecvCmd.Count > 0)
                        {
                            string strCmd = (string)m_qRecvCmd.Dequeue();
                            string[] strary = strCmd.Split(',');

                            LogManager.getInstance().Log("Run CMD:" + strCmd + "." + strCmd[1]);


                            switch (strCmd[1])
                            {
                                case 'G':
                                    if (strCmd.IndexOf("$GPRMC") == 0)
                                    {
                                        if (strary[2] == "A")
                                        {
                                            Form_Main.Main.setBoxStatus(BoxStatusItem.GPS, true);
                                            CmdTalker.getInstance().SetLastGPS(strCmd);

                                            try
                                            {
                                                //$GPRMC,040302.663,A,3939.7,N,10506.6,W,0.27,358.86,200804,,*1A
                                                if (dtLastSetSystemDT < System.DateTime.Now)
                                                {
                                                    LogManager.getInstance().Log("set SysTime:" + strCmd);

                                                    string[] straryGPRMC = strCmd.Split(',');
                                                    if (strary.Length > 9)
                                                    {
                                                        LogManager.getInstance().Log("set SysTime in:" + strCmd);

                                                        DeviceManager.SYSTEMTIME st = new DeviceManager.SYSTEMTIME();


                                                        st.wYear = System.Convert.ToUInt16("20" + straryGPRMC[9].Substring(4, 2));
                                                        st.wMonth = System.Convert.ToUInt16(straryGPRMC[9].Substring(2, 2));
                                                        st.wDay = System.Convert.ToUInt16(straryGPRMC[9].Substring(0, 2));
                                                        st.wHour = System.Convert.ToUInt16(straryGPRMC[1].Substring(0, 2));
                                                        st.wMinute = System.Convert.ToUInt16(straryGPRMC[1].Substring(2, 2));
                                                        st.wSecond = System.Convert.ToUInt16(straryGPRMC[1].Substring(4, 2));
                                                        st.wMilliseconds = 0;

                                                        /*DateTime dt = new DateTime(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
                                                        LogManager.getInstance().Log("get SysTime:" + dt.ToString("yy/MM/dd HH:mm:ss"));
                                                        dt = dt.AddHours(8);


                                                        st.wYear = System.Convert.ToUInt16(dt.Year);
                                                        st.wMonth =  System.Convert.ToUInt16(dt.Month);
                                                        st.wDay =  System.Convert.ToUInt16(dt.Day);
                                                        st.wHour =  System.Convert.ToUInt16(dt.Hour);
                                                        st.wMinute = System.Convert.ToUInt16( dt.Minute);
                                                        st.wSecond = System.Convert.ToUInt16( dt.Second);
                                                         */

                                                        DeviceManager.SetSystemTime(ref st);

                                                        DateTime dt = new DateTime(st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);

                                                        dtLastSetSystemDT = dtLastSetSystemDT.AddSeconds(60);

                                                        LogManager.getInstance().Log("set SysTime:" + dt.ToString("yy/MM/dd HH:mm:ss"));

                                                    }
                                                }

                                            }
                                            catch (Exception ex)
                                            {
                                                LogManager.getInstance().Log("set SysTime Error:" + strCmd, ex);
                                            }


                                        }
                                        else
                                            Form_Main.Main.setBoxStatus(BoxStatusItem.GPS, false);



                                    }

                                    break;

                                case 'Q':
                                    if (strCmd.Length >= 5 && strCmd.Substring(0, 5) == "$QUST")
                                    {
                                        if (strary[2] == "1")
                                        {
                                            Form_Main.Main.setBoxStatus(BoxStatusItem.GPRS, true);
                                        }
                                        else
                                        {

                                            Form_Main.Main.setBoxStatus(BoxStatusItem.GPRS, false);
                                        }
                                    }
                                    break;
                                case 'I':
                                    if (strLastInputStatus != strary[1])
                                    {

                                        if (strary[1][7] != strLastInputStatus[7])
                                        {
                                            LogManager.getInstance().Log("NoEQ7:" + strary[1][7] + " != " + strLastInputStatus[7]);
                                            if (strary[1][7] == '1')
                                            {
                                                Form_Main.Main.setBoxStatus(BoxStatusItem.ACC, true);
                                            }
                                            else if (strary[1][7] == '0')
                                            {
                                                Form_Main.Main.setBoxStatus(BoxStatusItem.ACC, false);
                                            }
                                        }
                                        if (strary[1][4] != strLastInputStatus[4])
                                        {
                                            LogManager.getInstance().Log("NoEQ4:" + strary[1][4] + " != " + strLastInputStatus[4]);
                                            if (strary[1][4] == '1') //Input 1 / 計程錶
                                            {
                                                if (Form_Main.Main.getCurrStatusChar() == "4")
                                                {
                                                    Form_Main.Main.SetCurrStatus(TaxiStatus.Free);
                                                }
                                            }
                                            else
                                            {
                                                if (Form_Main.Main.getCurrStatusChar() == "1" || Form_Main.Main.getCurrStatusChar() == "0" || Form_Main.Main.getCurrStatusChar() == "5")
                                                {
                                                    Form_Main.Main.SetCurrStatus(TaxiStatus.Pickup);
                                                }
                                            }
                                        }


                                        if (strary[1][6] != strLastInputStatus[6])
                                        {
                                            LogManager.getInstance().Log("NoEQ6:" + strary[1][6] + " != " + strLastInputStatus[6]);
                                            if (strary[1][6] == '1') // Input 3 / SOS
                                            {
                                                checkEMButton(true);

                                            }
                                            else
                                            {
                                                checkEMButton(false);
                                                Form_Main.Main.Screen_MainScreen.UnEmergency();
                                            }
                                        }
                                        strLastInputStatus = strary[1];




                                    }
                                    break;

                                case '!':
                                    LogManager.getInstance().Log("ADPCMD:" + strCmd);
                                    switch (strCmd.Substring(1, 4))
                                    {
                                        case "!A01":
                                            if (m_dtSOSDisable < System.DateTime.Now)
                                            {
                                                m_dtSOSDisable = System.DateTime.Now.AddSeconds(30);
                                                CmdTalker.getInstance().SendServer(Form_Main.Main.getCurrStatusChar() + "990");
                                            }
                                            break;
                                        case "!A02":
                                            if (m_dtSOSDisable < System.DateTime.Now)
                                            {
                                                m_dtSOSDisable = System.DateTime.Now.AddSeconds(30);
                                                CmdTalker.getInstance().SendServer(Form_Main.Main.getCurrStatusChar() + "930");
                                            }
                                            break;
                                        case "!A03": //Meter On
                                            switch (Form_Main.Main.getCurrStatusChar())
                                            {
                                                case "0":
                                                case "1":
                                                case "3":
                                                case "5":
                                                    Form_Main.Main.SetCurrStatus(TaxiStatus.Pickup);
                                                    SoundManager.getInstance().playPickup();
                                                    break;
                                                case "2":
                                                    Form_Main.Main.SetCurrStatus(TaxiStatus.Reach);
                                                    Form_Main.Main.SetCurrStatus(TaxiStatus.Pickup);
                                                    SoundManager.getInstance().playPickup();

                                                    break;
                                            }

                                            break;
                                        case "!A04": // Meter Off
                                            switch (Form_Main.Main.getCurrStatusChar())
                                            {
                                                case "4":
                                                    Form_Main.Main.SetCurrStatus(TaxiStatus.Free);
                                                    SoundManager.getInstance().playFree();
                                                    break;
                                            }

                                            break;


                                    }

                                    break;
                            }

                        }

                    }

                }
                string strServerCMD = "";
                if (m_bLogined)
                {
                    if (!m_sawp.Visible)
                    {
                        strServerCMD = CmdTalker.getInstance().checkServerCMD("%B");

                        if (strServerCMD != "")
                        {
                            Form_Main.Main.resetBackLightTimeout();
                            switch (strServerCMD[2])
                            {
                                case '1':
                                    ChangeToDispatchAsk(strServerCMD);
                                    break;
                                case '2':
                                    switch (strServerCMD[3])
                                    {
                                        case '1':
                                        case '2':
                                        case '5':
                                            StoreData.getInstance().addDispatch("10" + strServerCMD);
                                            break;
                                        case '3':
                                        case '4':
                                            StoreData.getInstance().addReserveJob("00" + strServerCMD);
                                            break;
                                    }
                                    ChangeToDispatchConfirm(strServerCMD);
                                    Screen_MainScreen.checkReserveJobButton();
                                    break;
                                case '0':
                                    //檢查訂單號碼

                                    string strOrderID = strServerCMD.Substring(3);

                                    if (strOrderID == Screen_MainScreen.RunOrderID)
                                    {
                                        StoreData.getInstance().addMsg("10" + "%C1" + System.DateTime.Now.ToString("yyMMddHHmmss") + "任務取消," + Screen_MainScreen.RunOrderText);
                                        Screen_MainScreen.sendBackCancelSuccess();
                                        Screen_MainScreen.setStatus(TaxiStatus.Free);
                                        ChangeToMessageRecv("%C1" + System.DateTime.Now.ToString("yyMMddHHmmss") + "任務取消," + Screen_MainScreen.RunOrderText);
                                    }
                                    else
                                    {
                                        string strJob = StoreData.getInstance().checkReserveJobCancel(strOrderID);
                                        if (strJob != "")
                                        {
                                            StoreData.getInstance().addMsg("10" + "%C1" + System.DateTime.Now.ToString("yyMMddHHmmss") + "預約任務取消," + strJob.Substring(21));
                                            Screen_MainScreen.sendBackCancelSuccess(strOrderID);
                                            ChangeToMessageRecv("%C1" + System.DateTime.Now.ToString("yyMMddHHmmss") + "預約任務取消," + strJob.Substring(21));
                                        }

                                    }

                                    Screen_MainScreen.checkReserveJobButton();
                                    break;
                            }
                        }
                    }

                    if (!m_dcp.m_IsDispatchConfirm && !m_sawp.Visible)
                    {
                        strServerCMD = CmdTalker.getInstance().checkServerCMD("%C");

                        if (strServerCMD != "")
                        {
                            Form_Main.Main.resetBackLightTimeout();
                            switch (strServerCMD[2])
                            {
                                case '0':
                                case '1':
                                    StoreData.getInstance().addMsg("00" + strServerCMD);
                                    ChangeToMessageRecv(strServerCMD);
                                    break;
                                case '2':
                                case '3':
                                    ChangeToMessageRecv(strServerCMD);
                                    break;
                            }
                        }

                        strServerCMD = CmdTalker.getInstance().checkServerCMD("%E");
                        if (strServerCMD != "")
                        {
                            Form_Main.Main.resetBackLightTimeout();
                            switch (strServerCMD[2])
                            {
                                //排班失敗
                                case '0':
                                    switch (Form_Main.Main.getCurrStatusChar())
                                    {
                                        case "1":
                                            SetCurrStatus(TaxiStatus.Free);
                                            break;
                                    }
                                    break;

                                case '2':
                                    SetCurrStatus(TaxiStatus.Free);
                                    if (strServerCMD.Length > 2)
                                        ChangeToMessageRecv("000000000000000" + strServerCMD.Substring(3));
                                    else
                                        ChangeToMessageRecv("000000000000000強制除班..");
                                    break;


                                case 'S': //插班成功, 應切換至排班
                                    SetCurrStatus(TaxiStatus.Station);

                                    break;
                                case 'C':
                                    m_dtSOSDisable = System.DateTime.Now.AddSeconds(StoreData.getInstance().SOSDisableSecs);
                                    Screen_MainScreen.UnEmergency();
                                    break;
                                case 'M':

                                    StoreData.getInstance().setSReportItem(strServerCMD.Substring(3));
                                    break;
                            }
                        }
                    }

                    strServerCMD = CmdTalker.getInstance().checkServerCMD("%F");
                    if (strServerCMD != "")
                    {
                        Form_Main.Main.resetBackLightTimeout();
                        switch (strServerCMD[2])
                        {
                            //更改參數及時間
                            case '0':
                                StoreData.getInstance().RealTimeButtonMins = strServerCMD.Substring(3);
                                break;

                            case '1':
                                StoreData.getInstance().SupportButtonMins = strServerCMD.Substring(3);
                                break;
                            case '2':
                                StoreData.getInstance().CancelExtendMins = System.Convert.ToInt32(strServerCMD.Substring(3));
                                break;
                            case '3':
                                StoreData.getInstance().MissPnrExtendMins = System.Convert.ToInt32(strServerCMD.Substring(3));

                                break;
                            case '4':
                                StoreData.getInstance().StationJobMins = System.Convert.ToInt32(strServerCMD.Substring(3));

                                break;
                            case 'T': //設定TTS控制字串
                                StoreData.getInstance().TTSOpen = strServerCMD.Substring(3);
                                break;

                        }
                    }

                    strServerCMD = CmdTalker.getInstance().checkServerCMD("%S");
                    if (strServerCMD != "")
                    {
                        Form_Main.Main.resetBackLightTimeout();
                        switch (strServerCMD[2])
                        {
                            //更改參數及時間
                            case 'T':
                                StoreData.getInstance().WaitTimeoutSecs = System.Convert.ToInt32(strServerCMD.Substring(3));
                                break;
                            case 'I':
                                switch (strServerCMD[3])
                                {
                                    case '1':
                                        StoreData.getInstance().ServerIP1 = strServerCMD.Substring(4);
                                        break;

                                    case '2':
                                        StoreData.getInstance().ServerIP2 = strServerCMD.Substring(4);
                                        break;
                                }

                                break;

                        }
                    }




                }

                bool bChecked = false;

                //TODO:設定ACC檢查
                /*
                if ( !m_bIsInitialing && dtCheckBoxAcc < System.DateTime.Now)
                {
                    bChecked = true;
                    CmdTalker.getInstance().SendCMD("AT$GETPDS");
                    dtCheckBoxAcc = System.DateTime.Now.Add(new TimeSpan(0, 0, 2));
                    if(dtCheckBox.AddMilliseconds(-300) < System.DateTime.Now)
                        dtCheckBox = System.DateTime.Now.AddMilliseconds(300);
                }*/

                //check與車機間的狀態
                /*
                if (!bChecked && !m_bIsInitialing && dtCheckBox < System.DateTime.Now)
                {
                    bChecked = true;
                    CmdTalker.getInstance().SendCMD("AT$QUST");
                    dtCheckBox = System.DateTime.Now.Add(new TimeSpan(0, 0, 8));
                }
                */

                if (!bChecked && !m_bIsInitialing && dtLastServerCheck < System.DateTime.Now)
                {
                    Form_Main.Main.Screen_MainScreen.sendCurrStatus();
                    updateLastServerCheck();
                }




            }
            catch (Exception ex)
            {
                if (button_Log.Visible)
                {
                    MessageBox.Show(ex.Message);
                    string strStackT = ex.StackTrace;
                    int nLen = strStackT.Length;
                    MessageBox.Show(ex.StackTrace.Substring(0, nLen / 2));
                    MessageBox.Show(ex.StackTrace.Substring(nLen / 2));
                }
            }
            finally
            {
                m_bIsTimer = false;
            }

            if (m_bEMButtonStatus && m_dtEMButtonHold < System.DateTime.Now)
            {
                m_bEMButtonStatus = false;
                Form_Main.Main.Screen_MainScreen.sendEMStatus(false);
            }
        }

        bool m_bEMButtonStatus = false;
        DateTime m_dtEMButtonHold = System.DateTime.Now;

        private void checkEMButton(bool arg_b)
        {
            if (arg_b)
            {
                m_dtEMButtonHold = System.DateTime.Now.AddMilliseconds(2000);
            }
            m_bEMButtonStatus = arg_b;
        }



        public void button_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        private bool m_bIsInitialing = false;
        public void button_Initial_Click(object sender, EventArgs e)
        {
            bool bSuccess = false;
            //先關閉查詢及GPRMC傳送
            int n = 0;
            /*
            while (!bSuccess && n < 10)
            {
                try
                {
                    m_bIsInitialing = true;
                    CmdTalker.getInstance().SendCMD("AT$GPSPT=0,1");

                    string strIMEITemp = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$IMEI", 5, "IMEI:");
                    strIMEITemp = strIMEITemp.Split(':')[1];
                    strIMEITemp = strIMEITemp.Split('\r')[0];
                    m_strIMEI = strIMEITemp;
                    LogManager.getInstance().Log("IMEI:" + m_strIMEI);
                    System.Threading.Thread.Sleep(3000);

                    string strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$MODID=" + m_strIMEI + "", 5, "OK");

                    m_strIMEI = strIMEITemp.Substring(strIMEITemp.Length - 10);
                    LogManager.getInstance().Log("IMEI:" + m_strIMEI);
                    System.Threading.Thread.Sleep(3000);

                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$HOSTS=1,0," + StoreData.getInstance().ServerIP1, 5, "OK");
                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$HOSTS=2,0," + StoreData.getInstance().ServerIP2, 5, "OK");
                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$APN=" + StoreData.getInstance().APNCODE, 3, "OK");
                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$IPTYPE=1", 3, "OK");

                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$PDSR=3,30,25,0,2,0,0,1,0", 3, "OK");

                    //strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$PDSR=1,30,25,0,2,0,0,1,0", 3, "OK");

                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$RETRY=3,10", 3, "OK");
                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$NETCFG=3,0", 3, "OK");
                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$GPSPT=32,6", 3, "OK");
                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$FORMAT=0", 3, "OK"); //ASCII
                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$BAUD=1,4", 3, "OK");
                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$GPRSEN=1", 3, "OK");
                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$HB=0", 3, "OK");
                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$IGNEN=1,2,0,0", 3, "OK");//當ACC變化時傳資料
                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$IGN=5", 3, "OK");//Acc Debounce為5秒
                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$IN1EN=1,2,0,0", 3, "OK");//當Input1變化時傳資料, 用來做為警急按鈕用
                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$IN1=2", 3, "OK");//Input1 Debounce為2秒
                    //目前沒用到 strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$IN2EN=1,2,0,0", 3, "OK");//當Input2變化時傳資料
                    //strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$IN2=2", 3, "OK");//Input2 Debounce為2秒
                    //IN3(Positive)做為計費器連錶用, 不用設定, 由AT$GETPDS 來取得狀態變換

                    strResult = CmdTalker.getInstance().SendCMDAndWaitResponse("AT$TOW=20,5,3", 3, "OK");//設定拖吊警示

                    bSuccess = true;
                }
                catch (Exception ex)
                {
                    LogManager.getInstance().Log("Initial Error", ex);
                    System.Threading.Thread.Sleep(2000);
                    n++;
                }
                finally
                {
                    m_bIsInitialing = false;
                }
            }

            if (n < 10 && bSuccess)
            {
                MessageBox.Show("初始化成功..");
            }
            else
            {
                MessageBox.Show("初始化失敗, 請確認線路已接好..");

            }
             */
            //再啟動查詢


        }




        public void button_Log_Click(object sender, EventArgs e)
        {
            if (this.button_Log.Tag != "Y")
            {
                this.button_Log.Tag = "Y";


                string strTemp = LogManager.getInstance().getLog();
                while (strTemp != "")
                {
                    this.listBox_Log.Items.Insert(0, strTemp);
                    strTemp = LogManager.getInstance().getLog();
                }

                while (this.listBox_Log.Items.Count > 200)
                    this.listBox_Log.Items.RemoveAt(this.listBox_Log.Items.Count - 1);
                
                
                this.listBox_Log.Visible = true;
                this.listBox_Log.BringToFront();


            }
            else
            {
                this.button_Log.Tag = "N";
                this.listBox_Log.Visible = false;
                this.listBox_Log.SendToBack();
            }
        }

        private void Form_Main_LostFocus(object sender, EventArgs e)
        {
            

        }



        /* 設定全螢幕
        protected override void OnLoad(EventArgs e)
        {

            SHFullScreen(this.Handle, SHFS_HIDETASKBAR |
                SHFS_HIDESIPBUTTON | SHFS_HIDESTARTICON);

            base.OnLoad(e);
        }

        private const int SHFS_SHOWTASKBAR = 0x0001;
        private const int SHFS_HIDETASKBAR = 0x0002;
        private const int SHFS_SHOWSIPBUTTON = 0x0004;
        private const int SHFS_HIDESIPBUTTON = 0x0008;
        private const int SHFS_SHOWSTARTICON = 0x0010;
        private const int SHFS_HIDESTARTICON = 0x0020;

        [DllImport("aygshell")]
        static extern bool SHFullScreen(IntPtr hwnd, int dwState);
         */
    }

    /*
    public class MsgWindow : MessageWindow
    {
        // Assign integers to messages.
        // Note that custom Window messages start at WM_USER = 0x400.
        public const int WM_USER = 0x400;
        public const int REMSG_SETTOP = WM_USER + 9100;


        // Create an instance of the form.

        // Save a reference to the form so it can
        // be notified when messages are received.
        public MsgWindow()
        {
        }

        protected override void WndProc(ref Message m)
        {
            LogManager.getInstance().Log("RCV MSG:" + m.HWnd.ToString() + ",Msg:" + m.Msg);

            if (m.HWnd == Form_Main.Main.Handle)
            {
                LogManager.getInstance().Log("RCV MSG:" + m.HWnd.ToString() + ",Msg:" + m.Msg);
                if (m.Msg == REMSG_SETTOP)
                {
                    LogManager.getInstance().Log("RCV MSG: setTop");

                    Form_Main.Main.SetTopMost(true);
                }
            }
            base.WndProc(ref m);
        }
    }*/
}